import {createRouter, createWebHashHistory} from 'vue-router'
import {jumpRoute} from 'xhyk-vue'
import JumpRouteVue from 'xhyk-vue/xhLayout/theme/jumpRoute.vue'
import ErrorVue from 'xhyk-vue/xhUI/xhyk/error/xhykError.vue'
import MenuIndex from 'xhyk-vue/xhLayout/xhykMenuIndex.vue'
import {var_menu_getMenuFn} from "@/utils/varTool.js";

// region 路由绑定
const mainRoute = [
  {
    path: '/',
    redirect: '/shouYe',
  },
  {
    path: '/',
    name: 'mainIndex',
    component: MenuIndex,
    children: [
      {
        path: '/shouYe',
        name: 'shouYe',
        component: () => import('/src/views/shouYe/shouYe.vue'),
        meta: {
          title: '首页'
        }
      },
      {
        path: '/jumpRoute',
        name: 'jumpRoute',
        component: JumpRouteVue
      },
      {
        name: '404',
        path: '/404',
        component: ErrorVue,
        meta: {
          title: '404'
        }
      }
    ]
  }
]

const routes = []
routes.push(...mainRoute)
// 这个要放到最后面，配置上面以为的都重定向到404页面
routes.push(jumpRoute)

// endregion

// region 路由对象
export const router = createRouter({
  history: createWebHashHistory(),
  linkActiveClass: 'xhyk',
  routes
})
// endregion


// region 路由拦截

const whiteList = ['/shouYe']

// 全局访问前拦截
router.beforeEach(async (to, from, next) => {
  const path = to.path.toLowerCase()

  const isWhite = whiteList.find(row => row.toLowerCase() == path)


  if (isWhite) {
    // 跳转到首页
    if (path == '/404' && window.$piniaTheme.menuList.length <= 0) {
      const tempUrl = "/shouYe"
      const newPath = `/jumpRoute?toFullPath=${encodeURIComponent(tempUrl)}` +
          `&toPath=${encodeURIComponent(tempUrl)}`

      next(newPath)
      return
    }

    next()
    return
  }

  if (window.$pinia.authorIds.length <= 0) {
    await var_menu_getMenuFn()
  }

  next()
})


// endregion

export default router
